<template>
  <div class="dog-management">
    <!-- 顶部操作区域 -->
    <div class="header-actions">
      <div class="page-title">
        <h1>狗狗品种管理系统</h1>
        <p>管理和查看各种狗狗品种信息</p>
      </div>
      <div class="action-buttons">
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="showImportDialog"
          :loading="importing">
          导入品种数据
        </el-button>
        <el-button
          type="info"
          icon="el-icon-setting"
          @click="goToSceneConfig">
          场景配置
        </el-button>
        <el-button
          type="info"
          icon="el-icon-setting"
          @click="goToPetReactionConfig">
          配置反应
        </el-button>
        <el-button
          type="success"
          icon="el-icon-goods"
          @click="goToInventoryManagement">
          物品与奖励管理
        </el-button>
        <el-button
          type="warning"
          icon="el-icon-s-opportunity"
          @click="goToMoodConfig">
          心情配置
        </el-button>
      </div>
    </div>

    <!-- 狗狗列表 -->
    <DogList
      ref="dogList"
      @view-details="viewDetails"
      @refresh="refreshList"
    />

    <!-- 详情弹窗 -->
    <DogDetail
      :visible.sync="detailVisible"
      :dog-data="selectedDog"
      @edit-dog="editDogFromDetail"
      @refresh-list="refreshList"
    />

    <!-- 导入数据弹窗 -->
    <el-dialog
      title="导入狗狗品种数据"
      :visible.sync="importDialogVisible"
      width="500px"
      :close-on-click-modal="false">
      <div class="import-content">
        <div class="import-tips">
          <el-alert
            title="导入说明"
            type="info"
            :closable="false"
            show-icon>
            <div slot="description">
              <p>• 支持Excel (.xlsx, .xls) 和CSV (.csv) 格式文件</p>
              <p>• 文件大小不超过10MB</p>
              <p>• 请确保数据格式正确，参考模板文件</p>
            </div>
          </el-alert>
        </div>

        <div class="upload-area">
          <el-upload
            ref="upload"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :limit="1"
            :file-list="fileList"
            drag
            accept=".xlsx,.xls,.csv">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xlsx/xls/csv文件，且不超过10MB</div>
          </el-upload>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelImport">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmImport"
          :loading="importing"
          :disabled="!selectedFile">
          确认导入
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DogList from '@/components/DogList.vue'
import DogDetail from '@/components/DogDetail.vue'
import DogService from '@/api/dogService.js'

export default {
  name: 'DogManagement',
  components: {
    DogList,
    DogDetail
  },
  data() {
    return {
      detailVisible: false,
      selectedDog: {},
      importDialogVisible: false,
      importing: false,
      selectedFile: null,
      fileList: []
    }
  },
  methods: {
    editDogFromDetail(dog) {
      this.detailVisible = false
      this.$router.push(`/dogs/edit/${dog.id}`)
    },
    viewDetails(dog) {
      this.selectedDog = { ...dog }
      this.detailVisible = true
    },
    addNewBreed() {
      this.$router.push('/dogs/add')
    },
    goToSceneConfig() {
      this.$router.push('/scene-config')
    },
    goToPetReactionConfig() {
      this.$router.push('/pet-reaction-configs')
    },
    goToInventoryManagement() {
      this.$router.push('/items-and-rewards')
    },
    goToMoodConfig() {
      this.$router.push('/mood-config')
    },
    goToRewardConfig() {
      this.$router.push('/reward-config')
    },
    showImportDialog() {
      this.importDialogVisible = true
      this.selectedFile = null
      this.fileList = []
    },
    cancelImport() {
      this.importDialogVisible = false
      this.selectedFile = null
      this.fileList = []
      this.$refs.upload.clearFiles()
    },
    handleFileChange(file, fileList) {
      this.selectedFile = file.raw
      this.fileList = fileList
    },
    beforeUpload(file) {
      const isValidType = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                          'application/vnd.ms-excel',
                          'text/csv'].includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        this.$message.error('只能上传 Excel 或 CSV 格式的文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return false // 阻止自动上传
    },
    async confirmImport() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择要导入的文件')
        return
      }

      this.importing = true
      try {
        const result = await DogService.importBreeds(this.selectedFile)

        if (result.success) {
          this.$message.success(result.message)
          this.importDialogVisible = false
          this.refreshList() // 刷新列表
        } else {
          this.$message.error(result.message)
        }
      } catch (error) {
        this.$message.error('导入失败：' + error.message)
      } finally {
        this.importing = false
        this.selectedFile = null
        this.fileList = []
      }
    },
    refreshList() {
      // 通知子组件刷新数据
      this.$refs.dogList && this.$refs.dogList.loadDogs()
    },
    // 加载品种数据的方法，供子组件调用
    async loadBreedsData() {
      try {
        const result = await DogService.getBreedsList()
        return result
      } catch (error) {
        console.error('加载品种数据失败:', error)
        return {
          success: false,
          message: error.message || '加载失败'
        }
      }
    }
  }
}
</script>

<style scoped>
.dog-management {
  min-height: 100vh;
  background-color: #f8fafc;
}

.header-actions {
  background: white;
  padding: 24px 32px;
  margin-bottom: 0;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
}

.page-title p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.action-buttons {
  display: flex;
}

.action-buttons .el-button {
  margin-left: 12px;
}

.action-buttons .el-button:first-child {
  margin-left: 0;
}

.import-content {
  padding: 20px 0;
}

.import-tips {
  margin-bottom: 24px;
}

.upload-area {
  margin-top: 20px;
}

.upload-area .el-upload-dragger {
  width: 100%;
  height: 180px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.upload-area .el-upload-dragger:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.upload-area .el-icon-upload {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.upload-area .el-upload__text {
  color: #606266;
  font-size: 14px;
}

.upload-area .el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: flex-start;
    padding: 20px;
  }

  .header-actions .page-title {
    margin-bottom: 16px;
  }

  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }

  .page-title h1 {
    font-size: 24px;
  }
}
</style>
